﻿namespace CamlQueryCreator.Common
{
    /// <summary>
    /// Элемент CAML-запроса для сортировки результатов.
    /// </summary>
    public abstract class CamlOrderElement : CamlBase
    {
        private readonly string _fieldName;
        private readonly bool _isAscending;

        /// <summary>
        /// Элемент CAML-запроса для сортировки результатов.
        /// <para>Конструктор.</para>
        /// </summary>
        protected CamlOrderElement(CamlBase parentBuilder, string fieldName, bool isAscending)
            : base(parentBuilder)
        {
            _fieldName = fieldName;
            _isAscending = isAscending;
        }

        protected string GetRefFieldQuery()
        {
            var ascendingValue = _isAscending ? null : " Ascending='FALSE'";
            return string.Format(
                "<FieldRef Name='{0}'{1}/>", _fieldName, ascendingValue);
        }

        /// <summary>
        /// Сортировка.
        /// </summary>
        public CamlOrderAdditionElement AndOrderBy(IListFieldInfoBase fieldInfo, bool isAscending = true)
        {
            return new CamlOrderAdditionElement(this, fieldInfo, isAscending);
        }

        /// <summary>
        /// Сортировка.
        /// </summary>
        public CamlOrderAdditionElement AndOrderBy(string fieldName, bool isAscending = true)
        {
            return new CamlOrderAdditionElement(this, fieldName, isAscending);
        }
    }
}
